package com.it.gmall.product.service;

import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class TestServiceImpl implements TestService {
    @Autowired
    private RedisTemplate redisTemplate;

    /*不上锁*/
    /*@Override
    public void test() {
        Integer num = (Integer) redisTemplate.opsForValue().get("num");
        num++;
        redisTemplate.opsForValue().set("num",num);
    }*/

    /*本地锁*/
    /*private final Lock lock = new ReentrantLock();
    @Override
    public void test() {
        lock.lock();
        Integer num = (Integer) redisTemplate.opsForValue().get("num");
        num++;
        redisTemplate.opsForValue().set("num",num);
        lock.unlock();
    }*/

    /*分布式事务锁*/
    @Override
    public void test() {
        // 向redis中设置锁
        // Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent("lock", "11");
        // 防止死锁
        // Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent("lock", "11",3, TimeUnit.SECONDS);
        // 防止误删
        String uuid = UUID.randomUUID().toString();
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent("lock", uuid,3, TimeUnit.SECONDS);

        if(ifAbsent){// 设置成功 里面没锁
            Integer num = (Integer) redisTemplate.opsForValue().get("num");
            num++;
            redisTemplate.opsForValue().set("num",num);

            // 删除1：解锁(删除)
            // redisTemplate.delete("lock");

            // 删除2：防止误删 在删除之前先判断是不是自己的那把锁
            /*Object lock = redisTemplate.opsForValue().get("lock");//获取
            if(uuid.equals(lock)){ // 说明是同一把锁
                redisTemplate.delete("lock");
            }*/

            // 删除3：在删除锁的时候保证原子性 redis本身是单线程的 所以可以使用redis
            // lua脚本
            String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
            redisTemplate.execute(new DefaultRedisScript<>(script), Collections.singletonList("lock"), uuid);


        }else{// 设置失败 已经上锁
            test();
        }

    }
}
